package com.example.baselib.http;

import android.util.Log;


import com.example.baselib.http.base64.Base64Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class HttpBaseParamsInterceptor implements Interceptor {
    private String key = "038962-f87c443599@a689e4-041Ff48";
    private String urlpath;
    private String parmContent;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //这个是请求的url，也就是咱们前面配置的baseUrl
        String url = request.url().toString();
        //这个是请求方法
        String method = request.method();
        urlpath = url+method;
        long t1 = System.nanoTime();
        request = encrypt(request);//模拟的加密方法
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        response = decrypt(response);
        return response;
    }

    /**
     * 添加基础参数
     */
    private String addParameter() {
        String result = "";
        //String uuid = SPUtil.read(Constants.USERINFO, "uuid", "");
        //String token = SPUtil.read(Constants.USERINFO, "token", "");
        JSONObject jsonObject = new JSONObject();
        try {
//            if (!TextUtils.isEmpty(uuid)){
//                jsonObject.put("createUserId",uuid);
//                jsonObject.put("uuid",uuid);
//                jsonObject.put("userId",uuid);
//            }
            jsonObject.put("version", "1");
            //jsonObject.put("os", Constants.OS);
            String s = jsonObject.toString();
            int length = s.length() - 1;
            result = s.substring(1, length) + ",";
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 请求体加密
     */
    private Request encrypt(Request request) throws IOException {
        //String token = SPUtil.read(Constants.USERINFO, "token", "");
        //获取请求body，只有@Body 参数的requestBody 才不会为 null
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            if (buffer.size() > 0) {
                parmContent = insertString(buffer.readString(charset), addParameter(), 1);
            } else {
                parmContent = buffer.readString(charset);
            }

//            insertString(buffer.readString(charset),addParameter(),1)
            try {
                String encrypt = Base64Util.encrypt(parmContent, key);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("requestData", encrypt);
                String content = jsonObject.toString();
                RequestBody body = MultipartBody.create(contentType, content);
                request = request.newBuilder()
                        //.header("token", token)
                        .post(body)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            request = request.newBuilder()
                    //.header("token", token)
                    .build();
        }
        return request;
    }

    /**
     * 响应体解密
     */
    private Response decrypt(Response response) throws IOException {
        if (response.isSuccessful()) {
            //the response data
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = Charset.defaultCharset();
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String content = buffer.clone().readString(charset);
            try {
                JSONObject jsonObject = new JSONObject(content);
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    String data = jsonObject.getString("data");
                    String decrypt = Base64Util.decrypt(data, key);
                    ResponseBody responseBody = ResponseBody.create(contentType, decrypt);
                    Log.e("请求链接", "{"+urlpath+"}");
                    Log.e("请求参数", parmContent);
                    Log.e("请求响应", decrypt);
                    response = response.newBuilder()
                            .body(responseBody)
                            .build();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public String insertString(String src, String dec, int position) {
        StringBuffer stringBuffer = new StringBuffer(src);
        return stringBuffer.insert(position, dec).toString();
    }
}
